/*
 * PGN_Reader : A simple pgn reader for chess games.
 * Copyright (C) 2011 Laurent BERNABE
 * 
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <http://www.gnu.org/licenses/>.
 */
package com.gmail.bernabe.laurent.java_swing.pgn_reader.gui;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JPanel;

import com.gmail.bernabe.laurent.java_swing.pgn_reader.processing.PlayingTape;

public class BoardButtonsJPanel extends JPanel {
	
	public BoardButtonsJPanel(PlayingTape playingTapePointer){
		this.playingTapePointer = playingTapePointer;
		setLayout(new FlowLayout(FlowLayout.CENTER, 10, 10));
		rollbackButton.setEnabled(false);
		forwardButton.setEnabled(true);
		add(rollbackButton);
		add(forwardButton);
		saveButtonsStates();
		
		rollbackButton.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent event) {
				BoardButtonsJPanel.this.playingTapePointer.backward();
			}
			
		});
		
		forwardButton.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent event) {
				Thread forwardThread  = new Thread(new Runnable() {
					
					@Override
					public void run() {
						BoardButtonsJPanel.this.playingTapePointer.forward();
					}
				});
				forwardThread.setName("FowardThread : "+forwardThread.getName());
				forwardThread.start();
			}
			
		});
	}
	
	public void setEnabled(boolean mustBeEnabled){
		if (mustBeEnabled)
			restoreOldButtonsStates();
		else {
			saveButtonsStates();
			disableAllButtons();
		}
	}

	private void disableAllButtons() {
		rollbackButton.setEnabled(false);
		forwardButton.setEnabled(false);
	}

	private void saveButtonsStates() {
		registeredEnabledStates[0] = rollbackButton.isEnabled();
		registeredEnabledStates[1] = forwardButton.isEnabled();
	}

	private void restoreOldButtonsStates() {
		rollbackButton.setEnabled(registeredEnabledStates[0]);
		forwardButton.setEnabled(registeredEnabledStates[1]);
	}

	private static final long serialVersionUID = 1L;
	private PlayingTape playingTapePointer;
	private JButton rollbackButton = new JButton(" < ");
	private JButton forwardButton = new JButton(" > ");
	
	private boolean [] registeredEnabledStates = new boolean[2];

}
